//
//  InstallmentViewController.m
//  Rich
//
//  Created by Kenny Chen on 13/7/13.
//  Copyright (c) 2013年 Kenny Chen. All rights reserved.
//

#import "InstallmentViewController.h"

@interface InstallmentViewController ()

@end

@implementation InstallmentViewController

@synthesize currencyCode;
@synthesize date;
@synthesize amount;
@synthesize times;
@synthesize downPayment;
@synthesize annualInterestRate;
@synthesize period;
@synthesize isModified;

- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        currencyCode = @"NTD";
        selectedPaymentRow = 0;
        
        [self reset];
        
        self.mode = RichTableModeCustom;
        
        [self initInstallmentPeriodPicker];
        [self initInputToolbar:RichInputToolbarButtonDefaultSet];
    }
    
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;
 
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
}

- (void)reset
{
    date = nil;
    amount = 0.0f;
    downPayment = 0.0f;
    annualInterestRate = 0.0f;
    times = 1;
    period = TransactionInstallmentPeriodMonthly;
    isModified = NO;
}

- (BOOL)checkCorrectness
{
    if (times > 1) {
        if ((downPayment < amount) && (fmodf(amount - downPayment, times - 1) != 0))
            return NO;
    }
    else if (times == 0)
        times = 1;
    
    return YES;
}

- (double)calculateDownPayment
{
    return (double)((int)amount / times) + (double)((int)amount % ((int)amount / times)) + (double)(amount - (int)amount);
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    if ([self checkCorrectness] && downPayment == 0)
        downPayment = [self calculateDownPayment];
    
    [self.tableView reloadData];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 3;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0)
        return 4;
    else if (section == 1)
        return 2;
    else if ([self checkCorrectness])
        return times;
    else
        return 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section;
{
    return 20;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    return [super tableView:tableView viewForHeaderInSection:section];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = nil;
    NSDate *installmentDate;
    
    // Configure the cell...
    
    if ([indexPath section] == 0) {
        tableCellStyle = RichTableCellStyleTextfield;
        RichTableViewTextfieldCell *textfieldCell = (RichTableViewTextfieldCell *)[super tableView:tableView cellForRowAtIndexPath:indexPath];
        
        cell = textfieldCell;
        
        textfieldCell.textfield.tag = [indexPath row];
        textfieldCell.textfield.inputView = nil;   /* Remove previous input view */
        
        switch ([indexPath row]) {
            case 0:
                if (selectedPaymentRow == 0) {
                    textfieldCell.textLabel.text = RichLocaleString(@"Number of Payments");
                    textfieldCell.textfield.text = [NSString stringWithFormat:@"%lu", times];
                    textfieldCell.userInteractionEnabled = YES;
                    textfieldCell.textfield.textColor = [UIColor blackColor];
                }
                else {
                    textfieldCell.textLabel.text = RichLocaleString(@"Payment #");
                    textfieldCell.textfield.text = [NSString stringWithFormat:@"%lu", selectedPaymentRow + 1];
                    textfieldCell.userInteractionEnabled = NO;
                    textfieldCell.textfield.textColor = [UIColor grayColor];
                }
                
                textfieldCell.textfield.returnKeyType = UIReturnKeyNext;
                textfieldCell.textfield.keyboardType = UIKeyboardTypeDecimalPad;
                break;
                
            case 1:
                if (selectedPaymentRow == 0) {
                    textfieldCell.textLabel.text = RichLocaleString(@"Down Payment");
                    textfieldCell.textfield.text = [NSString stringWithFormat:[[RichDelegate core] currencyDecimalFormatString:currencyCode], downPayment];
                    textfieldCell.userInteractionEnabled = YES;
                    textfieldCell.textfield.textColor = [UIColor blackColor];
                }
                else {
                    textfieldCell.textLabel.text = [NSString stringWithFormat:RichLocaleString(@"Amount of Payment #%d"), selectedPaymentRow + 1];
                    textfieldCell.textfield.text = [[RichDelegate core] currencyFormatWithSign:
                                                    [[RichDelegate core] calculateLoanPayment:amount - downPayment
                                                                                        times:times
                                                                                   annualRate:annualInterestRate]
                                                                                          code:currencyCode];
                    textfieldCell.userInteractionEnabled = NO;
                    textfieldCell.textfield.textColor = [UIColor grayColor];
                }
                
                textfieldCell.textfield.returnKeyType = UIReturnKeyNext;
                textfieldCell.textfield.keyboardType = UIKeyboardTypeDecimalPad;
                break;
                
            case 2:
                textfieldCell.textLabel.text = RichLocaleString(@"Annual Interest Rate");
                textfieldCell.textfield.returnKeyType = UIReturnKeyNext;
                textfieldCell.textfield.text = [NSString stringWithFormat:@"%2.3f", annualInterestRate];
                textfieldCell.textfield.keyboardType = UIKeyboardTypeDecimalPad;
                
                if (selectedPaymentRow == 0) {
                    textfieldCell.userInteractionEnabled = YES;
                    textfieldCell.textfield.textColor = [UIColor blackColor];
                }
                else {
                    textfieldCell.userInteractionEnabled = NO;
                    textfieldCell.textfield.textColor = [UIColor grayColor];
                }
                
                break;
                
            case 3:
                if (selectedPaymentRow > 0) {
                    textfieldCell.userInteractionEnabled = NO;
                    textfieldCell.textfield.textColor = [UIColor grayColor];
                }
                else {
                    textfieldCell.userInteractionEnabled = YES;
                    textfieldCell.textfield.textColor = [UIColor blackColor];
                }
                
                textfieldCell.textLabel.text = RichLocaleString(@"Period");
                textfieldCell.textfield.returnKeyType = UIReturnKeyDone;
                textfieldCell.textfield.inputView = installmentPeriodPicker;
                textfieldCell.textfield.text = [[RichDelegate core] stringFromInstallmentPeriod:period];
                break;
        }
    }
    else if ([indexPath section] == 1) {
        tableCellStyle = RichTableCellStyleDefault;
        cell = [super tableView:tableView cellForRowAtIndexPath:indexPath];
        
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        if ([indexPath row] == 0) {
            cell.textLabel.text = @"Total Amount";
            cell.detailTextLabel.text = [NSString stringWithFormat:[[RichDelegate core] currencyDecimalFormatString:currencyCode], amount];
        }
        else if ([indexPath row] == 1) {
            cell.textLabel.text = @"Loan Amount";
            cell.detailTextLabel.text = [NSString stringWithFormat:[[RichDelegate core] currencyDecimalFormatString:currencyCode], amount - downPayment];
        }
    }
    else {
        if ([self checkCorrectness]) {
            tableCellStyle = RichTableCellStyleDefault;
            cell = [super tableView:tableView cellForRowAtIndexPath:indexPath];
            
            if ([indexPath row] > 0) {
                NSDateComponents *dateComponents = [[NSDateComponents alloc] init];
                if (period == TransactionInstallmentPeriodMonthly)
                    [dateComponents setMonth:[indexPath row]];
                else if (period == TransactionInstallmentPeriodQuarterly)
                    [dateComponents setMonth:[indexPath row] * 3]; // FIXME: [Installment] Calculate correct month of quarterly period
                else if (period == TransactionInstallmentPeriodSemiannual)
                    [dateComponents setMonth:[indexPath row] * 6]; // FIXME: [Installment] Calculate correct month of semiannual period
                else
                    [dateComponents setYear:[indexPath row]];
                NSCalendar *calendar = [NSCalendar currentCalendar];
                installmentDate = [calendar dateByAddingComponents:dateComponents toDate:date options:0];
                [dateComponents release];
            }
            else
                installmentDate = date;
            
            cell.textLabel.text = [NSString stringWithFormat:@"%@ (#%lu)",
                                   [[RichDelegate core] stringFromDate:installmentDate format:@"yyyy-MM-dd"], [indexPath row] + 1];
            
            if ([indexPath row] == 0) {
                cell.detailTextLabel.text = [[RichDelegate core] currencyFormatWithSign:downPayment code:currencyCode];
            }
            else {
                cell.detailTextLabel.text = [[RichDelegate core] currencyFormatWithSign:
                                             [[RichDelegate core] calculateLoanPayment:amount - downPayment
                                                                                 times:times
                                                                            annualRate:annualInterestRate]
                                                                                   code:currencyCode];
            }
        }
        else {
            tableCellStyle = RichTableCellStyleMessage;
            cell = [super tableView:tableView cellForRowAtIndexPath:indexPath];
            cell.textLabel.text = @"Invalid installment setting";
        }
    }
    
    return cell;
}

/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    }   
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
{
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Navigation logic may go here. Create and push another view controller.
    /*
     <#DetailViewController#> *detailViewController = [[<#DetailViewController#> alloc] initWithNibName:@"<#Nib name#>" bundle:nil];
     // ...
     // Pass the selected object to the new view controller.
     [self.navigationController pushViewController:detailViewController animated:YES];
     [detailViewController release];
     */
    
    if ([indexPath section] == 2) {
        selectedPaymentRow = [indexPath row];
        [self.tableView reloadSections:[NSIndexSet indexSetWithIndex:0] withRowAnimation:UITableViewRowAnimationAutomatic];
    }
}

#pragma mark - Toolbar button actions

- (void)toolbarDidPressNextButton:(UIBarButtonItem *)sender
{
    [self textFieldDidEndEditing:currentTextfield];
    [self.tableView reloadData];
    [super toolbarDidPressNextButton:sender];
}

- (void)toolbarDidPressDoneButton:(UIBarButtonItem *)sender
{
    [super toolbarDidPressDoneButton:sender];
    [self.tableView reloadData];
}


#pragma mark - Textfield delegate

- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    [super textFieldDidBeginEditing:textField];
    
    //self.tableView.contentInset = UIEdgeInsetsMake(0, 0, 240, 0);
    [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:textField.tag inSection:0]
                          atScrollPosition:UITableViewScrollPositionBottom animated:YES];
}

- (void)textFieldDidEndEditing:(UITextField *)textField
{
    [super textFieldDidEndEditing:textField];
    
    switch (textField.tag) {
        case 0:
            times = [textField.text intValue];
            
            if (times > 0) {
                downPayment = [self calculateDownPayment];
            }
            
            break;
        case 1:
            downPayment = [textField.text floatValue];
            break;
        case 2:
            if (selectedPaymentRow == 0) {
                annualInterestRate = [textField.text doubleValue];
            }
            
            break;
    }
    
    isModified = YES;
}

#pragma mark - Picker view delegate and datasource

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)tableComponents
{
    [super pickerView:pickerView didSelectRow:row inComponent:tableComponents];
    period = row + 1;
}

@end
